<template>
  <view class="game-container" v-if="isVisible">
    <!-- 游戏标题栏 -->
    <view class="game-header">
      <text class="game-title">太空打飞机</text>
      <view class="game-stats">
        <text class="score">分数: {{ score }}</text>
        <text class="lives">生命: {{ lives }}</text>
      </view>
      <view class="game-controls">
        <button v-if="gameState === 'playing'" class="pause-btn" @click="pauseGame">暂停</button>
        <button class="close-btn" @click="closeGame">关闭</button>
      </view>
    </view>
    
    <!-- 游戏画布 -->
    <canvas canvas-id="planeGame" class="game-canvas" @touchstart="onTouchStart" @touchmove="onTouchMove"></canvas>
    
    <!-- 游戏开始界面 -->
    <view class="start-screen" v-if="gameState === 'ready'">
      <text class="start-title">太空打飞机</text>
      <text class="start-subtitle">点击开始游戏</text>
      <text class="game-instructions">
        触摸屏幕移动你的飞机，
        避开敌机并消灭它们！
      </text>
      <button class="start-btn" @click="startGame">开始</button>
    </view>
    
    <!-- 游戏结束界面 -->
    <view class="end-screen" v-if="gameState === 'over'">
      <text class="end-title">游戏结束</text>
      <text class="final-score">最终分数: {{ score }}</text>
      <text class="high-score">最高分: {{ highScore }}</text>
      <button class="restart-btn" @click="restartGame">再来一局</button>
    </view>
    
    <!-- 暂停菜单 -->
    <view class="pause-screen" v-if="gameState === 'paused'">
      <text class="pause-title">游戏暂停</text>
      <button class="resume-btn" @click="resumeGame">继续</button>
      <button class="restart-btn" @click="restartGame">重新开始</button>
    </view>
  </view>
</template>

<script>
export default {
  name: 'PlaneGame',
  props: {
    isVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      gameState: 'ready', // ready, playing, paused, over
      score: 0,
      lives: 3,
      highScore: 0,
      
      // 游戏对象
      player: {
        x: 0,
        y: 0,
        width: 60,
        height: 80,
        speed: 5,
        bullets: []
      },
      enemies: [],
      explosions: [],
      powerups: [],
      
      // 游戏参数
      canvasWidth: 0,
      canvasHeight: 0,
      enemySpeed: 3,
      enemySpawnRate: 1500, // ms
      bulletSpeed: 8,
      lastEnemySpawn: 0,
      lastPowerupSpawn: 0,
      powerupSpawnRate: 15000, // ms
      
      // 游戏循环
      gameLoop: null,
      ctx: null
    }
  },
  watch: {
    isVisible(newVal) {
      if (newVal) {
        this.initGame();
      } else {
        this.cleanupGame();
      }
    }
  },
  methods: {
    // 初始化游戏
    initGame() {
      // 获取canvas上下文
      this.ctx = uni.createCanvasContext('planeGame');
      
      // 获取canvas尺寸
      const query = uni.createSelectorQuery();
      query.select('.game-canvas')
        .fields({ size: true })
        .exec(res => {
          if (res[0]) {
            this.canvasWidth = res[0].width;
            this.canvasHeight = res[0].height;
            // 初始化玩家位置
            this.player.x = this.canvasWidth / 2 - this.player.width / 2;
            this.player.y = this.canvasHeight - this.player.height - 50;
            // 绘制初始界面
            this.drawStartScreen();
          }
        });
      
      // 加载最高分
      this.loadHighScore();
    },
    
    // 开始游戏
    startGame() {
      this.gameState = 'playing';
      this.score = 0;
      this.lives = 3;
      this.player.bullets = [];
      this.enemies = [];
      this.explosions = [];
      this.powerups = [];
      this.lastEnemySpawn = Date.now();
      this.lastPowerupSpawn = Date.now();
      
      // 启动游戏循环
      this.gameLoop = setInterval(() => {
        this.update();
        this.draw();
      }, 16); // 约60fps
    },
    
    // 暂停游戏
    pauseGame() {
      this.gameState = 'paused';
      if (this.gameLoop) {
        clearInterval(this.gameLoop);
        this.gameLoop = null;
      }
      this.drawPauseScreen();
    },
    
    // 恢复游戏
    resumeGame() {
      this.gameState = 'playing';
      this.lastEnemySpawn = Date.now();
      this.gameLoop = setInterval(() => {
        this.update();
        this.draw();
      }, 16);
    },
    
    // 重新开始游戏
    restartGame() {
      if (this.gameLoop) {
        clearInterval(this.gameLoop);
        this.gameLoop = null;
      }
      this.startGame();
    },
    
    // 游戏结束
    gameOver() {
      this.gameState = 'over';
      if (this.gameLoop) {
        clearInterval(this.gameLoop);
        this.gameLoop = null;
      }
      
      // 保存最高分
      if (this.score > this.highScore) {
        this.highScore = this.score;
        this.saveHighScore();
      }
      
      this.drawEndScreen();
    },
    
    // 关闭游戏
    closeGame() {
      this.cleanupGame();
      this.$emit('close');
    },
    
    // 清理游戏资源
    cleanupGame() {
      if (this.gameLoop) {
        clearInterval(this.gameLoop);
        this.gameLoop = null;
      }
      this.gameState = 'ready';
    },
    
    // 更新游戏状态
    update() {
      if (this.gameState !== 'playing') return;
      
      const now = Date.now();
      
      // 生成敌机
      if (now - this.lastEnemySpawn > this.enemySpawnRate) {
        this.spawnEnemy();
        this.lastEnemySpawn = now;
        
        // 随时间增加难度
        if (this.enemySpawnRate > 500) {
          this.enemySpawnRate -= 10;
        }
        if (this.enemySpeed < 8) {
          this.enemySpeed += 0.01;
        }
      }
      
      // 生成道具
      if (now - this.lastPowerupSpawn > this.powerupSpawnRate) {
        this.spawnPowerup();
        this.lastPowerupSpawn = now;
      }
      
      // 更新子弹
      this.updateBullets();
      
      // 更新敌机
      this.updateEnemies();
      
      // 更新爆炸效果
      this.updateExplosions();
      
      // 更新道具
      this.updatePowerups();
      
      // 检测碰撞
      this.checkCollisions();
    },
    
    // 生成敌机
    spawnEnemy() {
      const enemyTypes = [
        { width: 40, height: 40, color: '#ff6b6b', health: 1 },
        { width: 50, height: 50, color: '#4ecdc4', health: 2 },
        { width: 60, height: 60, color: '#ff9f1c', health: 3 }
      ];
      
      // 随机选择敌机类型
      const enemyType = enemyTypes[Math.floor(Math.random() * enemyTypes.length)];
      
      // 随机位置
      const x = Math.random() * (this.canvasWidth - enemyType.width);
      
      this.enemies.push({
        x,
        y: -enemyType.height,
        width: enemyType.width,
        height: enemyType.height,
        color: enemyType.color,
        health: enemyType.health,
        speed: this.enemySpeed + Math.random() * 2
      });
    },
    
    // 生成道具
    spawnPowerup() {
      const powerupTypes = [
        { type: 'health', color: '#4ecdc4', icon: '+' },
        { type: 'speed', color: '#ffe66d', icon: 'S' },
        { type: 'fireRate', color: '#ff6b6b', icon: 'F' }
      ];
      
      const powerupType = powerupTypes[Math.floor(Math.random() * powerupTypes.length)];
      const x = Math.random() * (this.canvasWidth - 30);
      
      this.powerups.push({
        x,
        y: -30,
        width: 30,
        height: 30,
        color: powerupType.color,
        type: powerupType.type,
        icon: powerupType.icon,
        speed: 3
      });
    },
    
    // 更新子弹
    updateBullets() {
      this.player.bullets = this.player.bullets.filter(bullet => {
        bullet.y -= bullet.speed;
        // 移除超出屏幕的子弹
        return bullet.y > -bullet.height;
      });
    },
    
    // 更新敌机
    updateEnemies() {
      this.enemies = this.enemies.filter(enemy => {
        enemy.y += enemy.speed;
        
        // 敌机到达屏幕底部，扣除生命值并创建爆炸效果
        if (enemy.y > this.canvasHeight) {
          this.lives--;
          this.createExplosion(enemy.x + enemy.width / 2, this.canvasHeight / 2);
          if (this.lives <= 0) {
            this.gameOver();
          }
          return false;
        }
        
        return true;
      });
    },
    
    // 更新爆炸效果
    updateExplosions() {
      this.explosions = this.explosions.filter(explosion => {
        explosion.life--;
        return explosion.life > 0;
      });
    },
    
    // 更新道具
    updatePowerups() {
      this.powerups = this.powerups.filter(powerup => {
        powerup.y += powerup.speed;
        return powerup.y < this.canvasHeight + powerup.height;
      });
    },
    
    // 检测碰撞
    checkCollisions() {
      // 先复制敌机数组，避免在循环中修改原数组导致的问题
      const remainingEnemies = [];
      
      // 遍历所有敌机进行碰撞检测
      for (let i = 0; i < this.enemies.length; i++) {
        const enemy = this.enemies[i];
        let enemyHit = false;
        let enemyDestroyed = false;
        
        // 检查子弹与敌机碰撞
        this.player.bullets = this.player.bullets.filter(bullet => {
          if (this.checkCollision(bullet, enemy)) {
            enemyHit = true;
            enemy.health--;
            
            if (enemy.health <= 0) {
              // 增加分数
              this.score += 100;
              // 创建爆炸效果
              this.createExplosion(enemy.x + enemy.width / 2, enemy.y + enemy.height / 2);
              enemyDestroyed = true;
            }
            return false;
          }
          return true;
        });
        
        // 如果敌机未被摧毁，检查玩家与敌机碰撞
        if (!enemyDestroyed && this.checkCollision(this.player, enemy)) {
          this.lives--;
          this.createExplosion(enemy.x + enemy.width / 2, enemy.y + enemy.height / 2);
          
          if (this.lives <= 0) {
            this.gameOver();
          }
          enemyDestroyed = true;
        }
        
        // 如果敌机未被摧毁，保留它
        if (!enemyDestroyed) {
          remainingEnemies.push(enemy);
        }
      }
      
      // 更新敌机数组
      this.enemies = remainingEnemies;
      
      // 玩家与道具碰撞
      this.powerups = this.powerups.filter(powerup => {
        if (this.checkCollision(this.player, powerup)) {
          this.applyPowerup(powerup);
          return false;
        }
        return true;
      });
    },
    
    // 检测两个矩形是否碰撞
    checkCollision(a, b) {
      return a.x < b.x + b.width &&
             a.x + a.width > b.x &&
             a.y < b.y + b.height &&
             a.y + a.height > b.y;
    },
    
    // 创建爆炸效果
    createExplosion(x, y) {
      this.explosions.push({
        x,
        y,
        radius: 10,
        maxRadius: 40,
        life: 15,
        color: '#ff9f1c'
      });
    },
    
    // 应用道具效果
    applyPowerup(powerup) {
      switch(powerup.type) {
        case 'health':
          this.lives = Math.min(5, this.lives + 1);
          break;
        case 'speed':
          this.player.speed = Math.min(10, this.player.speed + 1);
          setTimeout(() => {
            this.player.speed = Math.max(5, this.player.speed - 1);
          }, 10000);
          break;
        case 'fireRate':
          // 临时增加射速
          const originalRate = this.bulletSpeed;
          this.bulletSpeed = Math.min(12, this.bulletSpeed + 2);
          setTimeout(() => {
            this.bulletSpeed = originalRate;
          }, 8000);
          break;
      }
    },
    
    // 绘制游戏画面
    draw() {
      if (!this.ctx) return;
      
      // 清空画布
      this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
      
      // 绘制背景
      this.drawBackground();
      
      // 绘制玩家飞机
      this.drawPlayer();
      
      // 绘制子弹
      this.drawBullets();
      
      // 绘制敌机
      this.drawEnemies();
      
      // 绘制爆炸效果
      this.drawExplosions();
      
      // 绘制道具
      this.drawPowerups();
      
      // 绘制分数和生命值
      this.drawStats();
      
      // 绘制画布
      this.ctx.draw();
    },
    
    // 绘制背景
    drawBackground() {
      // 绘制星空背景
      this.ctx.fillStyle = '#0a0a1a';
      this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
      
      // 绘制星星
      this.ctx.fillStyle = '#ffffff';
      for (let i = 0; i < 50; i++) {
        const x = Math.random() * this.canvasWidth;
        const y = Math.random() * this.canvasHeight;
        const size = Math.random() * 2;
        this.ctx.beginPath();
        this.ctx.arc(x, y, size, 0, Math.PI * 2);
        this.ctx.fill();
      }
    },
    
    // 绘制玩家飞机
    drawPlayer() {
      // 绘制飞机主体
      this.ctx.fillStyle = '#667eea';
      this.ctx.beginPath();
      this.ctx.moveTo(this.player.x + this.player.width / 2, this.player.y);
      this.ctx.lineTo(this.player.x, this.player.y + this.player.height);
      this.ctx.lineTo(this.player.x + this.player.width, this.player.y + this.player.height);
      this.ctx.closePath();
      this.ctx.fill();
      
      // 绘制飞机窗口
      this.ctx.fillStyle = '#48bfe3';
      this.ctx.fillRect(
        this.player.x + this.player.width / 4,
        this.player.y + this.player.height / 4,
        this.player.width / 2,
        this.player.height / 3
      );
      
      // 绘制引擎火焰
      this.ctx.fillStyle = '#ff6b6b';
      this.ctx.beginPath();
      this.ctx.moveTo(this.player.x + this.player.width / 4, this.player.y + this.player.height);
      this.ctx.lineTo(this.player.x + this.player.width / 2, this.player.y + this.player.height + 15);
      this.ctx.lineTo(this.player.x + this.player.width * 3 / 4, this.player.y + this.player.height);
      this.ctx.closePath();
      this.ctx.fill();
    },
    
    // 绘制子弹
    drawBullets() {
      this.ctx.fillStyle = '#ff6b6b';
      this.player.bullets.forEach(bullet => {
        this.ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
      });
    },
    
    // 绘制敌机
    drawEnemies() {
      this.enemies.forEach(enemy => {
        this.ctx.fillStyle = enemy.color;
        
        // 绘制不同形状的敌机
        if (enemy.health === 1) {
          // 三角形敌机
          this.ctx.beginPath();
          this.ctx.moveTo(enemy.x + enemy.width / 2, enemy.y);
          this.ctx.lineTo(enemy.x, enemy.y + enemy.height);
          this.ctx.lineTo(enemy.x + enemy.width, enemy.y + enemy.height);
          this.ctx.closePath();
          this.ctx.fill();
        } else if (enemy.health === 2) {
          // 矩形敌机
          this.ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
        } else {
          // 圆形敌机
          this.ctx.beginPath();
          this.ctx.arc(enemy.x + enemy.width / 2, enemy.y + enemy.height / 2, enemy.width / 2, 0, Math.PI * 2);
          this.ctx.fill();
        }
        
        // 绘制敌机生命值条
        if (enemy.health > 1) {
          this.ctx.fillStyle = '#333';
          this.ctx.fillRect(enemy.x, enemy.y - 10, enemy.width, 5);
          this.ctx.fillStyle = '#4ecdc4';
          this.ctx.fillRect(enemy.x, enemy.y - 10, enemy.width * (enemy.health / 3), 5);
        }
      });
    },
    
    // 绘制爆炸效果
    drawExplosions() {
      this.explosions.forEach(explosion => {
        const alpha = explosion.life / 15;
        this.ctx.globalAlpha = alpha;
        this.ctx.fillStyle = explosion.color;
        this.ctx.beginPath();
        const radius = explosion.radius + (explosion.maxRadius - explosion.radius) * (1 - explosion.life / 15);
        this.ctx.arc(explosion.x, explosion.y, radius, 0, Math.PI * 2);
        this.ctx.fill();
        this.ctx.globalAlpha = 1;
      });
    },
    
    // 绘制道具
    drawPowerups() {
      this.powerups.forEach(powerup => {
        this.ctx.fillStyle = powerup.color;
        this.ctx.fillRect(powerup.x, powerup.y, powerup.width, powerup.height);
        this.ctx.fillStyle = '#ffffff';
        this.ctx.font = '20px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.textBaseline = 'middle';
        this.ctx.fillText(powerup.icon, powerup.x + powerup.width / 2, powerup.y + powerup.height / 2);
      });
    },
    
    // 绘制分数和生命值
    drawStats() {
      this.ctx.fillStyle = '#ffffff';
      this.ctx.font = '16px Arial';
      this.ctx.textAlign = 'left';
      this.ctx.fillText(`分数: ${this.score}`, 10, 30);
      
      // 绘制生命值图标
      this.ctx.fillText('生命:', 120, 30);
      for (let i = 0; i < this.lives; i++) {
        this.ctx.fillStyle = '#ff6b6b';
        this.ctx.beginPath();
        this.ctx.moveTo(180 + i * 20, 25);
        this.ctx.lineTo(170 + i * 20, 35);
        this.ctx.lineTo(180 + i * 20, 45);
        this.ctx.lineTo(190 + i * 20, 35);
        this.ctx.closePath();
        this.ctx.fill();
      }
    },
    
    // 绘制开始界面
    drawStartScreen() {
      if (!this.ctx) return;
      
      this.drawBackground();
      
      // 绘制标题
      this.ctx.fillStyle = '#ffffff';
      this.ctx.font = '40px Arial';
      this.ctx.textAlign = 'center';
      this.ctx.fillText('太空打飞机', this.canvasWidth / 2, this.canvasHeight / 2 - 80);
      
      // 绘制提示
      this.ctx.font = '20px Arial';
      this.ctx.fillText('点击开始游戏', this.canvasWidth / 2, this.canvasHeight / 2 + 50);
      
      this.ctx.draw();
    },
    
    // 绘制结束界面
    drawEndScreen() {
      if (!this.ctx) return;
      
      this.drawBackground();
      
      // 绘制标题
      this.ctx.fillStyle = '#ff6b6b';
      this.ctx.font = '40px Arial';
      this.ctx.textAlign = 'center';
      this.ctx.fillText('游戏结束', this.canvasWidth / 2, this.canvasHeight / 2 - 80);
      
      // 绘制分数
      this.ctx.fillStyle = '#ffffff';
      this.ctx.font = '24px Arial';
      this.ctx.fillText(`最终分数: ${this.score}`, this.canvasWidth / 2, this.canvasHeight / 2 - 20);
      this.ctx.fillText(`最高分: ${this.highScore}`, this.canvasWidth / 2, this.canvasHeight / 2 + 20);
      
      // 绘制提示
      this.ctx.font = '20px Arial';
      this.ctx.fillText('点击重新开始', this.canvasWidth / 2, this.canvasHeight / 2 + 80);
      
      this.ctx.draw();
    },
    
    // 绘制暂停界面
    drawPauseScreen() {
      if (!this.ctx) return;
      
      // 半透明遮罩
      this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
      this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
      
      // 绘制标题
      this.ctx.fillStyle = '#ffffff';
      this.ctx.font = '40px Arial';
      this.ctx.textAlign = 'center';
      this.ctx.fillText('游戏暂停', this.canvasWidth / 2, this.canvasHeight / 2 - 50);
      
      // 绘制按钮提示
      this.ctx.font = '20px Arial';
      this.ctx.fillText('继续', this.canvasWidth / 2 - 60, this.canvasHeight / 2 + 30);
      this.ctx.fillText('重新开始', this.canvasWidth / 2 + 60, this.canvasHeight / 2 + 30);
      
      this.ctx.draw();
    },
    
    // 触摸开始事件
    onTouchStart(e) {
      if (this.gameState === 'ready') {
        this.startGame();
        return;
      }
      
      if (this.gameState === 'playing') {
        // 发射子弹
        this.fireBullet();
      }
      
      // 更新玩家位置
      this.updatePlayerPosition(e);
    },
    
    // 触摸移动事件
    onTouchMove(e) {
      if (this.gameState === 'playing') {
        this.updatePlayerPosition(e);
      }
    },
    
    // 更新玩家位置
    updatePlayerPosition(e) {
      // 在uni-app环境中，优先从changedTouches获取触摸位置
      const touch = e.changedTouches && e.changedTouches[0] ? e.changedTouches[0] : (e.touches && e.touches[0] ? e.touches[0] : null);
      if (touch) {
        this.player.x = Math.max(0, Math.min(this.canvasWidth - this.player.width, touch.pageX - this.player.width / 2));
      }
    },
    
    // 发射子弹
    fireBullet() {
      this.player.bullets.push({
        x: this.player.x + this.player.width / 2 - 2,
        y: this.player.y - 10,
        width: 4,
        height: 15,
        speed: this.bulletSpeed
      });
      
      // 双发效果
      if (this.score > 500) {
        this.player.bullets.push({
          x: this.player.x + this.player.width / 2 - 15,
          y: this.player.y - 10,
          width: 4,
          height: 15,
          speed: this.bulletSpeed
        });
        this.player.bullets.push({
          x: this.player.x + this.player.width / 2 + 11,
          y: this.player.y - 10,
          width: 4,
          height: 15,
          speed: this.bulletSpeed
        });
      }
    },
    
    // 保存最高分
    saveHighScore() {
      try {
        uni.setStorageSync('planeGameHighScore', this.highScore);
      } catch (e) {
        console.error('保存最高分失败:', e);
      }
    },
    
    // 加载最高分
    loadHighScore() {
      try {
        const score = uni.getStorageSync('planeGameHighScore');
        if (score) {
          this.highScore = score;
        }
      } catch (e) {
        console.error('加载最高分失败:', e);
      }
    }
  },
  destroyed() {
    this.cleanupGame();
  }
}
</script>

<style scoped>
.game-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background: #0a0a1a;
  z-index: 9999;
  display: flex;
  flex-direction: column;
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background: rgba(10, 10, 26, 0.9);
  border-bottom: 2rpx solid #667eea;
}

.game-controls {
  display: flex;
  gap: 15rpx;
}

.game-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #ffffff;
}

.game-stats {
  display: flex;
  gap: 40rpx;
}

.score, .lives {
  font-size: 28rpx;
  color: #ffffff;
}

.close-btn {
  width: 120rpx;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 28rpx;
  background: #ff6b6b;
  color: #ffffff;
  border: none;
  border-radius: 8rpx;
  padding: 0;
}

.pause-btn {
  width: 120rpx;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 28rpx;
  background: #ff9f1c;
  color: #ffffff;
  border: none;
  border-radius: 8rpx;
  padding: 0;
}

.game-canvas {
  flex: 1;
  width: 100%;
  background: #0a0a1a;
}

.start-screen, .end-screen, .pause-screen {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.8);
}

.start-title, .end-title, .pause-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #ffffff;
  margin-bottom: 40rpx;
}

.start-subtitle {
  font-size: 28rpx;
  color: #cccccc;
  margin-bottom: 30rpx;
}

.game-instructions {
  font-size: 24rpx;
  color: #999999;
  text-align: center;
  margin-bottom: 60rpx;
  line-height: 40rpx;
}

.final-score, .high-score {
  font-size: 32rpx;
  color: #ffffff;
  margin-bottom: 20rpx;
}

.start-btn, .restart-btn, .resume-btn {
  width: 240rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
  background: #667eea;
  color: #ffffff;
  border: none;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.restart-btn {
  background: #4ecdc4;
}

.resume-btn {
  background: #ff9f1c;
  margin-right: 40rpx;
}
</style>